package org.wmq.positiontoshop.interceptor;

import com.alibaba.fastjson.JSON;
import io.netty.util.internal.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import org.wmq.positiontoshop.common.Result;
import org.wmq.positiontoshop.common.UserContext;
import org.wmq.positiontoshop.model.DO.User;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Component
@Slf4j
public class LoginInterceptor implements HandlerInterceptor {
    @Autowired
    private UserContext userContext;
    @Autowired
    private StringRedisTemplate redisTemplate;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("token");
        if (token == null){
            response.getWriter().write(JSON.toJSONString(Result.error("NOT_LOGIN")));
            log.error("user http header token is null");
            return false;
        }
        String userInfoJSON = this.redisTemplate.opsForValue().get("token:" + token);
        if (StringUtil.isNullOrEmpty(userInfoJSON)){
            response.getWriter().write(JSON.toJSONString(Result.error("NOT_LOGIN")));
            log.error("redis token is null");
            return false;
        }
        response.getWriter().write(JSON.toJSONString(Result.success()));
        User user = JSON.parseObject(userInfoJSON, User.class);
        log.info("user={} login success",user);
        UserContext.setUser(user);
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserContext.remove();
    }
}
